package cn.com.fssg.platform.base.handler.impl.fsadmin;

import cn.com.fssg.platform.base.handler.FormHandler;
import cn.com.fssg.platform.biz.BizUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CheckClassNameExtend implements FormHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();

    @Override
    public boolean afterSave(String formCode, String keyName, String keyValue, FormData formData) {
        //扩展对用户自定义handler表中 的class全局名称唯一性判断
        String className = formData.getMain().get("class_name").toString();
        if(StrUtil.isEmpty(className)) throw new RuntimeException("class全局名称不能为空");
        String sql = "SELECT * FROM cfg_custom_handler";
        sql = String.format("select * from (%s) t", sql);
        sql += " where (class_name = :className)";
        HashMap<String,Object> params = new HashMap<>();
        params.put("className", className);
        System.out.println("jdbcTemplate==null ? " + jdbcTemplate==null);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql,params);
        boolean exists = maps != null && maps.size() > 0;
        if(exists){
            Map<String, Object> map = maps.get(0);
            Object id = map.get(keyName);
            if(ObjectUtil.isNotEmpty(id) && id.equals(keyValue)) exists = false;
        }
        if (exists)  throw new RuntimeException(String.format("class全局名称: %s已存在，不允许重复", className));
        return true;
    }

    @Override
    public boolean afterInit(String formCode, String keyName, String keyValue, FormData formData) {
        //TODO
        return false;
    }

    @Override
    public boolean afterDelete(String formCode, String keyName, String keyValue, FormData formData) {
        //TODO
        return false;
    }

}
